package org.example.treehole.service.impl;

import org.example.treehole.mapper.CardMapper;
import org.example.treehole.pojo.dto.CardDto;
import org.example.treehole.pojo.entity.Card;
import org.example.treehole.pojo.other.PageBean;
import org.example.treehole.pojo.vo.CardVo;
import org.example.treehole.service.CardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CardServiceImpl implements CardService {
    @Autowired
    private CardMapper cardMapper;

    @Override
    public void postCard(CardDto cardDto) {
        CardVo cardVo = new CardVo();
//        cardVo.setOpenid(cardDto.getOpenid());
        cardVo.setOpenid("1234");
        cardVo.setContent(cardDto.getContent());
        // 获取当前的 LocalDateTime
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        cardVo.setPostTime(now);
        cardMapper.insert(cardVo);
    }

    @Override
    public List<Card> selectAllCard() {
        List<Card> cardList = cardMapper.selectAll();
        return cardList;
    }

    @Override
    public PageBean pageCard(Integer page, Integer pageSize) {
        Long total = cardMapper.count();
        int totalPages = (int) Math.ceil((double) total / pageSize);
        int start = (int) (total-page*pageSize);
        if (page == totalPages) {
            pageSize = Math.toIntExact(total - (page - 1) * pageSize);
            start=0;
        }
        List<Card> pageCardList = cardMapper.page(start, pageSize);
        pageCardList.sort((card1, card2) -> Long.compare(card2.getId(), card1.getId()));
        PageBean pageBean = new PageBean(total,pageCardList);
        return pageBean;
    }
}
